<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\PostFavorite;
use App\Models\Notification;
use Illuminate\Http\Request;

class PostFavoriteController extends Controller
{
    /**
     * 收藏或取消收藏
     */
    public function toggle(Request $request, Post $post)
    {
        $user = $request->user();

        $favorite = PostFavorite::where('user_id', $user->id)
            ->where('post_id', $post->id)
            ->first();

        if ($favorite) {
            // 取消收藏
            $favorite->delete();

            return response()->json([
                'favorited' => false,
                'favorites_count' => $post->fresh()->favorites_count,
                'message' => '取消收藏成功'
            ]);
        } else {
            // 收藏
            $favorite = PostFavorite::create([
                'user_id' => $user->id,
                'post_id' => $post->id,
            ]);

            // 创建通知（不通知自己）
            if ($post->user_id !== $user->id) {
                Notification::create([
                    'user_id' => $post->user_id,
                    'type' => 'favorite',
                    'notifiable_type' => PostFavorite::class,
                    'notifiable_id' => $favorite->id,
                    'from_user_id' => $user->id,
                    'title' => '新的收藏',
                    'content' => $user->name . ' 收藏了你的文章《' . $post->title . '》',
                    'data' => [
                        'post_id' => $post->id,
                        'post_slug' => $post->slug,
                        'post_title' => $post->title,
                        'user_name' => $user->name,
                        'user_username' => $user->username,
                    ],
                ]);
            }

            return response()->json([
                'favorited' => true,
                'favorites_count' => $post->fresh()->favorites_count,
                'message' => '收藏成功'
            ]);
        }
    }

    /**
     * 获取用户收藏的文章
     */
    public function userFavorites(Request $request)
    {
        $user = $request->user();

        $favorites = PostFavorite::with(['post' => function ($query) {
            $query->with(['user', 'category', 'tags'])
                ->where('status', 'published')
                ->where('is_approved', true);
        }])
            ->where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        // 过滤掉已删除或未发布的文章
        $favorites->setCollection(
            $favorites->getCollection()->filter(function ($item) {
                return $item->post !== null;
            })
        );

        return response()->json([
            'favorites' => $favorites->items(),
            'pagination' => [
                'total' => $favorites->total(),
                'current_page' => $favorites->currentPage(),
                'per_page' => $favorites->perPage(),
                'last_page' => $favorites->lastPage(),
            ]
        ]);
    }

    /**
     * 检查用户是否收藏了文章
     */
    public function check(Request $request, Post $post)
    {
        $user = $request->user();

        if (!$user) {
            return response()->json(['favorited' => false]);
        }

        $favorited = PostFavorite::where('user_id', $user->id)
            ->where('post_id', $post->id)
            ->exists();

        return response()->json(['favorited' => $favorited]);
    }

    /**
     * 批量检查收藏状态
     */
    public function checkBatch(Request $request)
    {
        $request->validate([
            'post_ids' => 'required|array',
            'post_ids.*' => 'exists:posts,id',
        ]);

        $user = $request->user();

        if (!$user) {
            return response()->json([]);
        }

        $favorited = PostFavorite::where('user_id', $user->id)
            ->whereIn('post_id', $request->post_ids)
            ->pluck('post_id')
            ->toArray();

        $result = [];
        foreach ($request->post_ids as $postId) {
            $result[$postId] = in_array($postId, $favorited);
        }

        return response()->json($result);
    }
}